package com.sjr.easy.chat.app.controller;

import com.alibaba.fastjson2.JSON;
import com.sjr.easy.chat.app.dto.AppTokenInfo;
import com.sjr.easy.chat.app.utils.AppTokenManager;
import com.sjr.easy.chat.constants.FriendRequestReadStatusConstants;
import com.sjr.easy.chat.dto.Result;
import com.sjr.easy.chat.model.FriendRequest;
import com.sjr.easy.chat.model.User;
import com.sjr.easy.chat.service.FriendRequestService;
import com.sjr.easy.chat.service.UserService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class AppFriendRequestController {

    @Autowired
    private FriendRequestService friendRequestService;

    @Autowired
    private UserService userService;

    @Autowired
    private AppTokenManager appTokenManager;

    @Data
    @ApiModel("创建好友申请接口请求参数")
    static class CreateFriendRequestReqParams {
        @ApiModelProperty("申请目标人用户ID")
        private Long targetUserId;
    }

    @ApiOperation("创建好友申请")
    @PostMapping("/app/friendRequest/createFriendRequest")
    public Result<Object> createFriendRequest(@RequestBody CreateFriendRequestReqParams reqParams) {
        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        Objects.requireNonNull(reqParams.targetUserId, "目标用户ID不允许为空");
        AppTokenInfo tokenInfo = appTokenManager.getTokenInfo();

        FriendRequest friendRequest = new FriendRequest();
        friendRequest.setFromUserId(tokenInfo.getId());
        friendRequest.setTargetUserId(reqParams.targetUserId);
        friendRequest.setCreateTime(new Date());
        friendRequest.setReadStatus(FriendRequestReadStatusConstants.unread);
        friendRequest.setStatus(0);

        friendRequestService.addFriendRequest(friendRequest);
        return Result.success();
    }

    @Data
    static class GetFriendRequestListResultData {

        private Long currentUserId;

        private List<FriendRequestView> friendRequestViewList = new ArrayList<>();

        @Data
        static class FriendRequestView {
            @ApiModelProperty("")
            private Long id;

            @ApiModelProperty("申请发起人用户ID")
            private Long fromUserId;

            private UserView fromUser;

            @ApiModelProperty("申请目标人用户ID")
            private Long targetUserId;

            private UserView targetUser;

            @ApiModelProperty("好友申请备注")
            private String remark;

            @ApiModelProperty("")
            private Date createTime;

            @ApiModelProperty("读取状态 0 未读 1 已读")
            private Integer readStatus;

            @ApiModelProperty("申请状态 0、待处理 1、已通过 2、已拒绝 3、已过期")
            private Integer status;
        }

        @Data
        static class UserView {
            @ApiModelProperty("")
            private Long id;

            @ApiModelProperty("用户编号")
            private String code;

            @ApiModelProperty("用户头像")
            private String headPortrait;

            @ApiModelProperty("用户头像存储类型：http存储类型可以直接加载、local类型需要通过指定接口加载图片")
            private String headPortraitStoreType;

            @ApiModelProperty("昵称")
            private String nickname;
        }
    }

    @ApiOperation("获取好友申请列表")
    @GetMapping("/app/friendRequest/getFriendRequestList")
    public Result<GetFriendRequestListResultData> getFriendRequestList() {
        AppTokenInfo tokenInfo = appTokenManager.getTokenInfo();
        List<FriendRequest> friendRequestList = friendRequestService.selectByFromUserIdOrTargetUserId(tokenInfo.getId());

        Set<Long> userIdSet = new HashSet<>();
        for (FriendRequest friendRequest : friendRequestList) {
            userIdSet.add(friendRequest.getFromUserId());
            userIdSet.add(friendRequest.getTargetUserId());
        }
        Map<Long, User> userMap = ListUtils.emptyIfNull(userService.selectByIdList(userIdSet.stream().toList()))
                .stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        GetFriendRequestListResultData resultData = new GetFriendRequestListResultData();
        resultData.currentUserId = tokenInfo.getId();
        for (FriendRequest friendRequest : friendRequestList) {
            GetFriendRequestListResultData.FriendRequestView friendRequestView = new GetFriendRequestListResultData.FriendRequestView();

            BeanUtils.copyProperties(friendRequest, friendRequestView);

            friendRequestView.fromUser = new GetFriendRequestListResultData.UserView();
            User fromUser = userMap.get(friendRequestView.fromUserId);
            BeanUtils.copyProperties(fromUser, friendRequestView.fromUser);


            friendRequestView.targetUser = new GetFriendRequestListResultData.UserView();
            User targetUser = userMap.get(friendRequestView.targetUserId);
            BeanUtils.copyProperties(targetUser, friendRequestView.targetUser);

            resultData.friendRequestViewList.add(friendRequestView);
        }
        log.info("resultData:{}", JSON.toJSONString(resultData));
        return Result.success(resultData);
    }

    @Data
    static class BatchChangeReadStatus2ReadReqParams {
        List<Long> idList;
    }

    @ApiOperation("批量修改好友申请状态为已读")
    @PostMapping("/app/friendRequest/batchChangeReadStatus2Read")
    public Result<Object> batchChangeReadStatus2Read(@RequestBody BatchChangeReadStatus2ReadReqParams reqParams) {
        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        AppTokenInfo tokenInfo = appTokenManager.getTokenInfo();
        log.info("tokenInfo:{}", JSON.toJSONString(tokenInfo));
        Set<Long> idSet = friendRequestService.selectByTargetUserId(tokenInfo.getId())
                .stream()
                .map(FriendRequest::getId).collect(Collectors.toSet());
        for (Long id : ListUtils.emptyIfNull(reqParams.idList)) {
            if (!idSet.contains(id)) {
                log.error("请求参数异常:{}, {}", JSON.toJSONString(reqParams), JSON.toJSONString(idSet));
                return Result.error("参数异常");
            }
        }
        friendRequestService.batchChangeReadStatus2Read(reqParams.idList);
        return Result.success();
    }

    @Data
    static class AcceptFriendRequestReqParams {
        Long id;
    }

    @ApiOperation("通过好友申请")
    @PostMapping("/app/friendRequest/acceptFriendRequest")
    public Result<Object> acceptFriendRequest(@RequestBody AcceptFriendRequestReqParams reqParams) {
        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        Long friendRequestId = reqParams.id;
        Objects.requireNonNull(friendRequestId, "参数异常");
        friendRequestService.acceptFriendRequest(friendRequestId);
        return Result.success();
    }

    @Data
    static class RejectFriendRequestReqParams {
        Long id;
    }

    @ApiOperation("拒绝好友申请")
    @PostMapping("/app/friendRequest/rejectFriendRequest")
    public Result<Object> rejectFriendRequest(@RequestBody RejectFriendRequestReqParams reqParams) {
        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        Long friendRequestId = reqParams.id;
        Objects.requireNonNull(friendRequestId, "参数异常");
        friendRequestService.rejectFriendRequest(friendRequestId);
        return Result.success();
    }
}
